﻿using System.Reflection;

namespace AppFramework.DesignMode {
    /// <summary>
    /// 泛型单例抽象基类，支持延迟加载，该类的子类必需有且仅有一个私有构造函数，否则会抛出异常。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class Singleton<T>{

        private static readonly Lazy<T> mInstance = new Lazy<T>(() => {
            var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            if (ctors.Length != 1) {
                throw new InvalidOperationException(string.Format("单例类：{0}只允许有一个构造函数", typeof(T).FullName));
            }
            var ctor = ctors.FirstOrDefault(c => c.GetParameters().Length == 0 && c.IsPrivate);
            return ctor == null
                ? throw new InvalidOperationException(String.Format("单例类：{0}只允许有且只有一个私有无参构造函数", typeof(T).FullName))
                : (T)ctor.Invoke(null);
        }, true);

        public static T GetInstance() {
            return mInstance.Value;
        }

    }
}
